package com.pb.infra.oth.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pb.infra.oth.entity.common.ReportTree;

import java.util.List;
import java.util.Map;

/**
 * 构造报表下拉树
 *
 * @author liudebao
 * @date 2020/7/10
 */
public class ReportTreeUtil {
    private List<ReportTree> rootList;

    private List<ReportTree> bodyList;

    public ReportTreeUtil(List<ReportTree> rootList, List<ReportTree> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    public List<ReportTree> getTree() {
        if (bodyList != null && !bodyList.isEmpty()) {
            Map<String, String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(reportTree -> getChild(reportTree, map));
            return rootList;
        }
        return null;
    }

    public void getChild(ReportTree reportTree, Map<String, String> map) {
        List<ReportTree> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getId()))
                .filter(c -> c.getParentId().equals(reportTree.getId()))
                .forEach(c -> {
                    map.put(c.getId(), c.getParentId());
                    getChild(c, map);
                    childList.add(c);
                });
        reportTree.setNodes(childList);
    }
}
